<template>
  <div>
    <div class="demo-upload-list" v-for="(item,index) in uploadList" :key="index">
      <template v-if="item.status === 'finished'">
        <img :src="item.url">
        <div class="demo-upload-list-cover">
          <!-- <Icon type="ios-eye-outline" @click.native="handleView(item.name)"></Icon> -->
          <Icon type="ios-eye-outline" @click.native="handleView(item)"></Icon>
          <Icon v-if="viewModel" type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
        </div>
      </template>
      <template v-else>
        <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
      </template>
    </div>
    <!-- <div v-if="viewModel"> -->
        <Upload
          ref="upload"
          v-if="viewModel"
          :show-upload-list="false"
          :default-file-list="defaultList"
          :on-success="handleSuccess"
          :format="['jpg','jpeg','png']"
          :max-size="2048"
          :on-format-error="handleFormatError"
          :on-exceeded-size="handleMaxSize"
          :before-upload="handleBeforeUpload"
          multiple
          type="drag"
          :action="action"
          style="display: inline-block;width:58px;">
          <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="camera" size="20"></Icon>
          </div>
        </Upload>
    <!-- </div> -->
    <div v-else>
      <div v-if="!imgUploadViewModel" style="color: red;">
        图片未上传
      </div>
    </div>


    <Modal title="图片大图浏览" v-model="visible">
      <img :src="imageUrl" v-if="visible" style="width: 100%">
    </Modal>
  </div>
</template>
<script>

import { imageRemoteUrl } from "@/utils/imageConstant";

export default {
  name: "image-comp",
  data() {
    return {
      defaultList: [],
      imgName: "",
      visible: false,
      uploadList: [],
      baseAction: "http://localhost:8080/upload/uploadImg?identify=",
      action: "",
      imageBaseUrl: "http://localhost:9080",
      baseUploadDir: "/upload/",
      imageUrl: '',
      uploadType: '',
      uploadTypeDir: '',
      viewModel: true,
      imgUploadViewModel: true
    };
  },
  methods: {
    initByType(uploadType,optType,initImageStr){
      this.uploadType = uploadType;
      this.uploadTypeDir = uploadType +'/';
      this.action = this.baseAction + uploadType;

      this.viewModel = true;
      this.imgUploadViewModel = true;
      if(0 === optType){
        this.uploadList = [];
        this.defaultList = [];
      }else if(1 === optType){
        let echoLitpic = this.echoImages(initImageStr);
        this.defaultList = echoLitpic;
        this.uploadList = echoLitpic;
      }else if(2 === optType){
        let echoLitpic = this.echoImages(initImageStr);
        this.defaultList = echoLitpic;
        this.uploadList = echoLitpic;
        if(0 === echoLitpic.length){
          this.imgUploadViewModel= false;
        }else{
          this.imgUploadViewModel= true;
        };
        this.viewModel = false;
      } else {}
    },
    handleView (item) {
      // this.imageUrl = this.imageBaseUrl + this.baseUploadDir + this.uploadTypeDir + name;
      this.imageUrl = item.url;
      this.visible = true;
    },
    handleRemove (file) {
      console.log("========handleRemove========");
      console.log(file);
      const fileList = this.$refs.upload.fileList;
      this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);

      this.uploadList = this.$refs.upload.fileList;

      let fileListPathStr = this.uploadFileListToStr(this.$refs.upload.fileList);
      let returnPath = {
        flag: true,
        pathStr: fileListPathStr
      }
      this.$emit('on-remove-success',returnPath);

    },
    handleSuccess (res, file) {
      console.log("===============上传成功===============");
      console.log(res);
      console.log(file);
      if(res.success === true){
        let returnImg = res.result;
        let pathArr = returnImg.relativePaths.split('/');
        let pathLastStr = pathArr[pathArr.length-1];

        file.url = this.imageBaseUrl+ returnImg.relativePaths;
        file.name = pathLastStr;

        // this.$refs.upload.fileList.forEach(function(item){
        //   console.log(item);
        //   item.showProgress = true;
        // })

        this.uploadList = this.$refs.upload.fileList;
        // //bug 最后一个有时会是showProgress=false
        let fileListPathStr = this.uploadFileListToStr(this.$refs.upload.fileList);
        let returnPath = {
          flag: true,
          pathStr: fileListPathStr
        }
        this.$emit('on-add-success',returnPath);
      }
    },
    handleFormatError (file) {
      this.$Modal.warning({
          title: "上传文件格式错误提示窗口",
          content: file.name + ' 文件格式不正确，请选择jpg或者png文件'
      });
    },
    handleMaxSize (file) {
      this.$Modal.warning({
          title: "上传文件过大提示窗口",
          content: file.name + ' 文件太大，不能超过2M'
      });
    },
    handleBeforeUpload () {
      console.log(this.uploadList);
      console.log(this.$refs.upload.fileList);

      const check = this.uploadList.length < 5;
      if (!check) {
          this.$Modal.warning({
            title: "上传文件过多提示窗口",
            content: ' 最多上传5张图片'
        });

      }
      return check;
    },

    //编辑时图片回显(逗号字符串封装成对象)
    echoImages(imageUrlStr){
      var _this = this;
      if(null===imageUrlStr || ""===imageUrlStr){
        return [];
      }
      ("," === imageUrlStr.slice(-1)) ? imageUrlStr = imageUrlStr.substring(0,imageUrlStr.length-1) : imageUrlStr = imageUrlStr;  //首先判断尾部是否带逗号(其它端涉及图片编辑) 如果有--去除
      let imageUrlArr = imageUrlStr.split(',');
      var echoImagesArr = [];
      imageUrlArr.forEach(function(item){
        let pathArr = item.split('/');
        let pathLastStr = pathArr[pathArr.length-1];
        echoImagesArr.push({
          status: 'finished',
          name: pathLastStr,
          url: _this.imageBaseUrl + item
        })
      })
      return echoImagesArr;
    },
    uploadFileListToStr(uploadList) {
      var _this = this;
      var uploadListStr = "";
      uploadList.forEach(function(item){
        console.log(item);

        //注意：更新操作时，初始化对象中没有response,暂时使用：/upload/+name构成
        let itemPathStr = "";
        if(item.response){
          itemPathStr = item.response.result.relativePaths+",";
        }else{
          let itemReplaceUrl = item.url.replace(_this.imageBaseUrl, '');
          itemPathStr = itemReplaceUrl+",";
          //  itemPathStr = item.url+",";
          // itemPathStr = _this.baseUploadDir + _this.uploadTypeDir + item.name+",";
        }

        uploadListStr += itemPathStr;
      })
      if("" !== uploadListStr){
        uploadListStr = uploadListStr.substring(0,uploadListStr.length-1); //去除最后一个逗号
      }
        return uploadListStr;
    }

  },
  mounted() {
    // this.uploadList = this.$refs.upload.fileList;
    this.baseAction = imageRemoteUrl.baseAction,
    this.imageBaseUrl = imageRemoteUrl.imageBaseUrl,
    this.baseUploadDir = imageRemoteUrl.baseUploadDir
  }
};
</script>
<style>
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
/* .ivu-upload-drag{
  border: none;
} */
</style>
